import React, {
    useEffect,
    useLayoutEffect,
    useState,
    useCallback
} from "react";
import {
    useDispatch
} from "react-redux";
import Main from "./main";
import axiosMethod from "../util/axios";
import $ from "jquery";
import {message, Spin} from "antd";
import {getQueryVariable,removeToken} from "../util";
import CONFIG from "../util/config";
import "./app.scss";

const {
    originUrl,
    appAddr,
    imageAddr
} = CONFIG;

function App(props){
    const [init, setInit] = useState(false);
    const dispatch = useDispatch();
    const getBaseInfo = useCallback(()=>{  //获取系统信息和用户信息
        return new Promise((resolve, reject)=>{
            axiosMethod({
                type: "get",
                url: "/api/common/system/info",
                body: {},
                callback: function(res){
                    let baseUrl = res.baseUrl;
                    sessionStorage.setItem("baseUrl", baseUrl);
                    window._baseUrl = baseUrl;
                    dispatch({
                        type: "SET_SYSINFO",
                        data: res
                    })
                    let myToken = getQueryVariable("lg_tk")||sessionStorage.getItem("token")||localStorage.getItem("token");
                    if(!myToken){
                        message.warn("未获取到token");
                        // window.location.href = sessionStorage.getItem("baseUrl") + `login.html?lg_sysid=260&lg_preurl=${encodeURIComponent(removeToken(window.location.href))}`
                        // return;
                    }
                    let sign = false;
                    $("script").each((index, item)=>{
                        if($(item).attr("src") === baseUrl + "/UserMgr/Login/JS/CheckIsOnline2.js"){
                            sign = true;
                        }
                    })
                    if(!sign){
                        // let script = document.createElement("script");
                        // script.src = baseUrl + "/UserMgr/Login/JS/CheckIsOnline2.js";
                        // script.type = "text/javascript";
                        // script.onload = function(){
                        //     window._LgBase_initCheck(baseUrl, myToken, "260");
                        // }
                        // document.getElementsByTagName("head")[0].appendChild(script);
                    }
                    sessionStorage.setItem("token", myToken);
                    //获取用户信息
                    axiosMethod({
                        type: "get",
                        url: "/api/common/user",
                        body: {
                            token: myToken
                        },
                        callback: function(res){
                            if(!res){
                                message.warn("未获取到当前用户信息");
                                return;
                            }
                            //存储用户信息
                            dispatch({
                                type: "SET_USERINFO",
                                data: res
                            })
                            resolve(res);
                        }
                    });
                }
            });
        })
       
    }, [dispatch]);
    const getOnlineInfo = useCallback(()=>{  //获取身份信息
        return new Promise((resolve, reject)=>{
            let baseUrl = sessionStorage.getItem("baseUrl");
            axiosMethod({
                type: "get",
                url: "/BaseApi/Login/GetOnlineUserInfo",
                baseUrl,
                body: {
                    token: sessionStorage.getItem("token"),
                    appid: 260,
                    access_token: "66d5dbb07ac770bdf3f3381e07632f4a"
                },
                callback: function(res, info){
                    if(info.StatusCode !== 200){
                        reject("基础平台获取用户信息失败");
                        return;
                    }
                    sessionStorage.setItem("UserInfo", JSON.stringify(info.Data));
                    resolve();
                }
            });
        })
    }, []);
    const getIdentityInfo = useCallback((userInfo)=>{  //获取身份信息
        return new Promise((resolve, reject)=>{
            axiosMethod({
                type: "get",
                url: "/api/homepage/identity/list",
                body: {
                    userId: userInfo.userId,
                    schoolId: userInfo.schoolId
                },
                callback: function(res, info){
                    if(info.code !== "200"){
                        reject("获取身份信息失败");
                        return;
                    }
                    let identityCode = getQueryVariable("lg_ic");
                    let obj = res && res[0]? res[0]: {};
                    res.forEach((item)=>{
                        if(item.identityCode === identityCode){
                            obj = item;
                        }
                    })
                    dispatch({
                        type: "SET_CURRENTIDENTITY",
                        data: obj
                    })
                    dispatch({
                        type: "SET_IDENTITYLIST",
                        data: res? res: []
                    })
                    resolve();
                }
            });
        })
    }, [dispatch]);
    const getTermInfo = useCallback((userInfo)=>{  //获取当前学期信息
        return new Promise((resolve, reject)=>{
            axiosMethod({
                type: "get",
                url: "/api/common/school/term/current/info",
                body: {
                    eduId: userInfo.eduId
                },
                callback: function(res, info){
                    if(info.code !== "200"){
                        reject("获取当前学期信息失败");
                        return;
                    }
                    dispatch({
                        type: "SET_TERMINFO",
                        data: res
                    })
                    resolve();
                }
            })
        })
    }, [dispatch]);
    const getSysAddr = useCallback((userInfo)=>{ //获取各项目地址
        return new Promise((resolve, reject)=>{
            axiosMethod({
                type: "get",
                url: "/api/common/system/list",
                body: {
                    sysIds: "000,260,264,210,894,231,N11,491,Y01"
                },
                callback: function(res){
                    let addrObj = {};
                    res.forEach((item)=>{
                        addrObj[item.sysId] = item;
                    })
                    dispatch({
                        type: "SET_SYSADDR",
                        data: addrObj
                    })
                    resolve();
                }
            })
        })
        
    }, [dispatch]);
    const getStyle = useCallback((userInfo)=>{  ////获取用户皮肤设置
        return new Promise((resolve, reject)=>{
            axiosMethod({
                type: "get",
                url: "/api/user/style",
                body: {
                    userId: userInfo.userId,
                    eduId: userInfo.eduId
                },
                callback: function(res){
                    dispatch({
                        type: "SET_SKIN",
                        data: res
                    })
                    resolve();
                }
            })
        })
    }, [dispatch]);
    const getCommonData = useCallback(async() => {
        let userInfo = await getBaseInfo();
        Promise.all([getIdentityInfo(userInfo),getTermInfo(userInfo),getOnlineInfo(),getSysAddr(),getStyle(userInfo)])
        .then(()=>{
            
            setInit(true);
        })
        .catch((res)=>{
            message.warn(res);
            setTimeout(() => {
                // sessionStorage.removeItem("token");
                // localStorage.removeItem("token");
                // window.location.href = sessionStorage.getItem("baseUrl") + `login.html?lg_sysid=260&lg_preurl=${encodeURIComponent(removeToken(window.location.href))}`
            }, 1000);
        })
    }, [getBaseInfo, getIdentityInfo, getTermInfo, getOnlineInfo, getSysAddr, getStyle]);
    useEffect(()=>{
        getCommonData();
    }, [getCommonData]);
    if(!init){
        return <Spin className="app_load" spinning={true} tip="加载中..." />
    }
    return (
        <Main />
    )
}

export default App;